package com.redstar.HappyRefresh.audit;

import com.redstar.HappyRefresh.config.QiNiuConfig;
import com.redstar.HappyRefresh.constant.AuditStatus;
import com.redstar.HappyRefresh.mapper.VideoMapper;
import com.redstar.HappyRefresh.pojo.Video;
import com.redstar.HappyRefresh.pojo.VideoTask;
import com.redstar.HappyRefresh.response.AuditResponse;
import com.redstar.HappyRefresh.service.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class VideoPublishAuditService implements AuditService<VideoTask, VideoTask>, InitializingBean, BeanPostProcessor {

    @Autowired
    private FeedService feedService;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private InterestPushService interestPushService;
    @Autowired
    private TextAuditService textAuditService;
    @Autowired
    private ImageAuditService imageAuditService;
    @Autowired
    private VideoAuditService videoAuditService;
    @Autowired
    private FollowService followService;
    @Autowired
    private FileService fileService;

    private final int maximumPoolSize = 8;
    protected ThreadPoolExecutor executor;


    public void audit(VideoTask videoTask, Boolean auditQueueState) { // videoTask：封装发布视频，auditQueueState：申请快/慢审核
        if (auditQueueState) {
            new Thread(() -> { audit(videoTask); }).start();
        } else {
            audit(videoTask);
        }
    }

    @Override
    public VideoTask audit(VideoTask videoTask) { // 进行任务编排
        executor.submit(() -> {
            Video video = videoTask.getVideo();
            AuditResponse videoAuditResponse = new AuditResponse(AuditStatus.SUCCESS, "正常"); // 视频
            AuditResponse coverAuditResponse = new AuditResponse(AuditStatus.SUCCESS, "正常"); // 封面
            if (!videoTask.getNewState()) { // 新增的公开视频或原本私密的视频改为公开，都需要进行审核
                videoAuditResponse = videoAuditService.audit(QiNiuConfig.CNAME + "/" + fileService.getById(video.getUrl()).getFileKey());
                coverAuditResponse = imageAuditService.audit(QiNiuConfig.CNAME + "/" + fileService.getById(video.getCover()).getFileKey());
            } else if (!videoTask.getOldState()) { // 原本公开的视频转为私密
                interestPushService.deleteSystemStockIn(video);
                interestPushService.deleteSystemTypeStockIn(video);
                // 删除发件箱以及收件箱中的视频
                List<Long> fansList = followService.getFansList(null, video.getUserId());
                feedService.deleteOutBoxFeed(video.getUserId(), fansList, video.getId());
            }
            // 修改视频，新老视频标题简介不一致都需要审核
            Video oldVideo = videoTask.getOldVideo();
            AuditResponse titleAuditResponse = new AuditResponse(AuditStatus.SUCCESS, "正常"); // 标题
            AuditResponse descAuditResponse = new AuditResponse(AuditStatus.SUCCESS, "正常"); // 描诉
            if (oldVideo != null && !video.getTitle().equals(oldVideo.getTitle())) {
                titleAuditResponse = textAuditService.audit(video.getTitle());
            }
            if (oldVideo != null && !video.getDescription().equals(oldVideo.getDescription()) && !ObjectUtils.isEmpty(video.getDescription())) {
                descAuditResponse = textAuditService.audit(video.getDescription());
            }
            Integer videoAuditStatus = videoAuditResponse.getAuditStatus();
            Integer coverAuditStatus = coverAuditResponse.getAuditStatus();
            Integer titleAuditStatus = titleAuditResponse.getAuditStatus();
            Integer descAuditStatus = descAuditResponse.getAuditStatus();
            boolean f1 = Objects.equals(videoAuditStatus, AuditStatus.SUCCESS);
            boolean f2 = Objects.equals(coverAuditStatus, AuditStatus.SUCCESS);
            boolean f3 = Objects.equals(titleAuditStatus, AuditStatus.SUCCESS);
            boolean f4 = Objects.equals(descAuditStatus, AuditStatus.SUCCESS);
            if (f1 && f2 && f3 && f4) {
                video.setMsg("通过");
                video.setAuditStatus(AuditStatus.SUCCESS);
                interestPushService.pushSystemStockIn(video);
                interestPushService.pushSystemTypeStockIn(video);
                feedService.pusOutBoxFeed(video.getUserId(), video.getId(), video.getGmtCreated().getTime()); // 推入发件箱
            } else {
                if (!f1) {
                    video.setMsg("视频有违规行为: " + videoAuditResponse.getMsg());
                    video.setAuditStatus(videoAuditResponse.getAuditStatus());
                } else if (!f2) {
                    video.setMsg("封面有违规行为: " + coverAuditResponse.getMsg());
                    video.setAuditStatus(coverAuditResponse.getAuditStatus());
                }else if (!f3) {
                    video.setMsg("标题有违规行为: " + coverAuditResponse.getMsg());
                    video.setAuditStatus(coverAuditResponse.getAuditStatus());
                } else {
                    video.setMsg("简介有违规行为: " + coverAuditResponse.getMsg());
                    video.setAuditStatus(coverAuditResponse.getAuditStatus());
                }
                // 视频违规，改为私密视频
                video.setOpen(true);
            }
            videoMapper.updateById(video);
        });
        return null;
    }

    public boolean getAuditQueueState() {
        return executor.getTaskCount() < maximumPoolSize;
    }

    @Override
    public void afterPropertiesSet() {
        executor = new ThreadPoolExecutor(5, maximumPoolSize, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
    }
}
